import { usePermissionStore } from '@/stores/permission';
import { useUserStore } from '@/stores/user';
import { STORAGE_KEY, useTabStore } from '@/stores/tabs'; // ← 新增
import router, { RouteNameEnum } from './index';
import NProgress from 'nprogress';

const whiteList = ['/login', '/403', '/404']; // 白名单

router.beforeEach(async (to, from, next) => {
  NProgress.start();

  const userStore = useUserStore();
  const permissionStore = usePermissionStore();
  const tabStore = useTabStore();
  const hasToken = !!userStore.getToken();
  const isInLayout = to.matched.some((record) => record.name === RouteNameEnum.LAYOUT_ROOT);

  // 未登录 → 跳转登录页
  if (!hasToken) {
    if (whiteList.includes(to.path)) {
      next();
    } else {
      next(`/login?redirect=${encodeURIComponent(to.fullPath)}`);
    }
    NProgress.done();
    return;
  }

  // 检测是否跳出 Layout,如果是则清空 tabs 及对应缓存
  if (!isInLayout && to.matched.length > 0) {
    console.log('---->jin lai le', to.matched);
    tabStore.$reset();
    localStorage.removeItem(STORAGE_KEY);
  }

  // 没有用户信息 → 拉取用户信息 + 动态路由
  if (!userStore.userInfo) {
    try {
      await userStore.fetchUserInfo();
      await permissionStore.generateRoutes();
      next({ ...to, replace: true });
    } catch (error) {
      userStore.logout();
      next('/login');
    }
  } else {
    next();
  }

  NProgress.done();
});
